package com.yeskery.nut.application.jetty;

import com.yeskery.nut.application.NutApplication;
import com.yeskery.nut.application.NutServer;
import com.yeskery.nut.core.*;
import com.yeskery.nut.http.servlet.ServletRequest;
import com.yeskery.nut.http.servlet.ServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * JettyServer Controller请求处理器
 * @author sprout
 * @version 1.0
 * 2022-08-05 01:14
 */
public class ServletControllerHttpHandler extends AbstractHandler {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(ServletControllerHttpHandler.class.getName());

    /** Nut应用对象 */
    private final NutApplication nutApplication;

    /** 服务上下文 */
    private final ServerContext serverContext;

    /** 请求分发器 */
    private final Dispatcher dispatcher;

    /** Session管理器 */
    private final SessionManager sessionManager;

    /** 服务请求配置对象 */
    private final ServerRequestConfiguration serverRequestConfiguration;

    /** Nut 服务器 */
    private final NutServer nutServer;

    /**
     * 构建一个JettyServer Controller请求处理器
     * @param nutApplication Nut应用对象
     * @param serverContext 服务上下文
     * @param dispatcher 请求分发器
     * @param sessionManager 会话管理器
     * @param serverRequestConfiguration 服务请求配置对象
     * @param nutServer Nut服务器对象
     */
    public ServletControllerHttpHandler(NutApplication nutApplication, ServerContext serverContext, Dispatcher dispatcher,
                                        SessionManager sessionManager, ServerRequestConfiguration serverRequestConfiguration,
                                        NutServer nutServer) {
        this.nutApplication = nutApplication;
        this.serverContext = serverContext;
        this.dispatcher = dispatcher;
        this.sessionManager = sessionManager;
        this.serverRequestConfiguration = serverRequestConfiguration;
        this.nutServer = nutServer;
    }

    @Override
    public void handle(String s, Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
        try {
            request.setHandled(true);
            com.yeskery.nut.core.Request nutRequest = new ServletRequest(serverContext, sessionManager,
                    serverRequestConfiguration, httpServletRequest);
            Response nutResponse = new ServletResponse(nutApplication, httpServletResponse);
            //请求执行的方法
            nutServer.process(nutRequest, nutResponse, dispatcher, sessionManager);
        } catch (Exception e) {
            logger.log(Level.WARNING, "An Error Occurred While Closing The JettyServer Socket.", e);
            throw e;
        }
    }
}
